package com.yuxl.common.auth.repository;

import com.yuxl.common.auth.entity.AuthRole;
import com.yuxl.common.auth.entity.AuthUser;
import com.yuxl.common.auth.entity.AuthUserRole;
import com.yuxl.common.core.annotation.PostgreSqlRepository;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import com.yuxl.common.core.annotation.PostgreSqlRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author : yuxl
 * @create 2025/7/23 上午11:17
 */
@PostgreSqlRepository
public interface AuthUserRoleRepository extends ReactiveCrudRepository<AuthUserRole, Long> {

    @Query("""
            SELECT r.mark, r.name
            FROM auth_role r
            INNER JOIN auth_user_role ur ON r.mark = ur.role_mark
            WHERE ur.user_id = :userId
            """)
    Flux<AuthRole> findByUserId(Long userId);

    @Query("""
            SELECT r.mark, r.name
            FROM auth_role r
            INNER JOIN auth_user_role ur ON r.mark = ur.role_mark
            WHERE ur.user_id in (:userIds)
            """)
    Flux<AuthRole> findByUserIds(List<Long> userIds);

    @Query("""
            SELECT u.*
            FROM auth_user u
            INNER JOIN auth_user_role ur ON u.id = ur.user_id 
            WHERE ur.role_mark = :roleMark
            """)
    Flux<AuthUser> findByRoleMark(String roleMark);

    @Query("""
            SELECT u.*
            FROM auth_user u
            INNER JOIN auth_user_role ur ON u.id = ur.user_id 
            WHERE ur.role_mark in (:roleMarks)
            """)
    Flux<AuthUser> findByRoleMarks(List<String> roleMarks);


    @Query("""
            DELETE FROM auth_user_role WHERE user_id = :userId
            """)
    Mono<Long> deleteByUserId(Long userId);

    @Query("""
            DELETE FROM auth_user_role WHERE role_mark = :roleMark
            """)
    Mono<Long> deleteByRoleMark(String roleMark);

}
